package com.shire.shire_interface.service.welcome;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.shire.shire_interface.constants.Constants;
import com.shire.shire_interface.constants.WxConstants;
import com.shire.shire_interface.constants.WxErrorCode;
import com.shire.shire_interface.dao.welcome.WxWelcomTaskDao;
import com.shire.shire_interface.dao.welcome.WxWelcomeSettingDao;
import com.shire.shire_interface.model.cs.WxChat;
import com.shire.shire_interface.model.group.WxGroup;
import com.shire.shire_interface.model.group.WxGroupMember;
import com.shire.shire_interface.model.user.WxAccount;
import com.shire.shire_interface.model.welcome.WxWelcomTask;
import com.shire.shire_interface.model.welcome.WxWelcomTaskExample;
import com.shire.shire_interface.model.welcome.WxWelcomeSetting;
import com.shire.shire_interface.model.welcome.WxWelcomeSettingExample;
import com.shire.shire_interface.service.chat.WxChatService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class WxWelcomeSettingService {

    @Resource
    private WxWelcomeSettingDao wxWelcomeSettingDao;
    @Resource
    private WxWelcomTaskDao welcomTaskDao;
    @Resource
    private WxChatService chatService;

    public int insertSetting(WxWelcomeSetting wxWelcomeSetting) {

        return wxWelcomeSettingDao.insertSelective(wxWelcomeSetting);
    }

    public List<WxWelcomeSetting> selectByExample(WxWelcomeSettingExample example) {
        return wxWelcomeSettingDao.selectByExampleWithBLOBs(example);
    }

    public int deleteByPrimaryKey(Integer settingid) {
        return wxWelcomeSettingDao.deleteByPrimaryKey(settingid);
    }

    public WxWelcomeSetting selectByPrimaryKey(Integer settingid) {
        return wxWelcomeSettingDao.selectByPrimaryKey(settingid);
    }

    public int updateByPrimaryKey(WxWelcomeSetting wxWelcomeSettingWithBLOBs) {
        return wxWelcomeSettingDao.updateByPrimaryKeySelective(wxWelcomeSettingWithBLOBs);
    }
    public void checkWelcomResponse(WxAccount account, WxGroup group, List<WxGroupMember> newMembers){
        System.out.println("+++++++++++发送欢迎语任务1");
        WxWelcomeSettingExample settingExample = new WxWelcomeSettingExample();
        settingExample.createCriteria().andWxaccountidEqualTo(account.getWxid()).andGroupidsLike("%"+group.getGroupno()+"%").andStatusEqualTo(Constants.YesNo.YES.getCode());

        List<WxWelcomeSetting> settingList = wxWelcomeSettingDao.selectByExampleWithBLOBs(settingExample);

        System.out.println("发送欢迎语任务2" + group.getGroupno()+ " " + account.getWxid() + " " + Constants.YesNo.YES.getCode());
        List<WxWelcomeSetting> validSetting = new ArrayList<>();
        for (WxWelcomeSetting welcomeSetting : settingList) {
            if (group.getPersonnum() >= welcomeSetting.getMemberlimit()){
                validSetting.add(welcomeSetting);
            }
        }

        if (validSetting.size()<1) {
            System.out.println("+++++++++++发送欢迎语任务2");
            return;
        }
        boolean sent;

        for (WxWelcomeSetting setting : validSetting) {
            WxWelcomTaskExample taskExample = new WxWelcomTaskExample();
            taskExample.createCriteria().andSettingidEqualTo(setting.getId()).andWxgroupidEqualTo(group.getGroupno());
            List<WxWelcomTask> tasks = welcomTaskDao.selectByExample(taskExample);

            if (tasks.size() < 1)
                continue;

            WxWelcomTask taskItem = tasks.get(0);
            if (taskItem.getUpdatetime()!=null && ((new Date()).getTime() - taskItem.getUpdatetime().getTime()) < (long)(setting.getTimeinterval()*1000)){
                continue;
            }

            if (setting.getMsgextra().startsWith("{")) {
                JSONObject jsonObject = JSONObject.parseObject(setting.getMsgextra());
                WxChat chat = new WxChat();
                chat.setWxaccount(account.getWxid());
                chat.setMsgid(String.valueOf((new Date()).getTime()));
                chat.setFriendwxid(group.getGroupno());
                chat.setFriendNick(group.getGroupname());
                chat.setAvatar(group.getAvatar());
                chat.setChatfrom(WxConstants.ChatFrom.SELF.getCode());
                chat.setContent(setting.getMsgextra());
                chat.setMsgtype(jsonObject.getInteger("msgtype"));
                chat.setSendstatus(WxErrorCode.INIT_VALUE);
                chat.setReadstatus(Constants.YesNo.YES.ordinal());
                chat.setFromplat(0);
                chat.setShowstatus(Constants.YesNo.YES.getCode());
                chat.setCsid(account.getCsid());
                chat.setCreatetime(new Date());
                chat.setReadtime(new Date());
                chatService.sendChatByCmd(chat);
                chatService.sendToKf(chat, group);
                sent = true;
            }else{
                JSONArray msgArray = JSONArray.parseArray(setting.getMsgextra());
                for (Object msg : msgArray) {
                    JSONObject msgItem = (JSONObject) msg;
                    WxChat chat = new WxChat();
                    chat.setWxaccount(account.getWxid());
                    chat.setMsgid(String.valueOf((new Date()).getTime()));
                    chat.setFriendwxid(group.getGroupno());
                    chat.setFriendNick(group.getGroupname());
                    chat.setAvatar(group.getAvatar());
                    chat.setChatfrom(WxConstants.ChatFrom.SELF.getCode());
                    chat.setContent(msgItem.toJSONString());
                    chat.setMsgtype(msgItem.getInteger("msgtype"));
                    chat.setSendstatus(WxErrorCode.INIT_VALUE);
                    chat.setReadstatus(Constants.YesNo.YES.ordinal());
                    chat.setFromplat(0);
                    chat.setShowstatus(Constants.YesNo.YES.getCode());
                    chat.setCsid(account.getCsid());
                    chat.setCreatetime(new Date());
                    chat.setReadtime(new Date());
                    System.out.println("+++++++++++发送欢迎语");
                    chatService.sendChatByCmd(chat);
                    chatService.sendToKf(chat, group);
                }
                sent = true;
            }

            if (setting.getAtfriend() != null && setting.getAtfriend() == 1){
                for (WxGroupMember newMember : newMembers) {
                    JSONObject atObject = new JSONObject();
//                    toUserWxId:发送给某个用户wxID或者alias.
// msg:发送的文本.
// at:
                    if (StringUtils.isBlank(newMember.getNick())|| StringUtils.isBlank(newMember.getWxid()))
                    {
                        continue;
                    }
                    atObject.put("content", "@"+newMember.getNick() + "\u2005");
                    atObject.put("wxid",newMember.getWxid());
                    atObject.put("msgtype", 1);
                    WxChat chat = new WxChat();
                    chat.setWxaccount(account.getWxid());
                    chat.setMsgid(String.valueOf((new Date()).getTime()));
                    chat.setFriendwxid(group.getGroupno());
                    chat.setFriendNick(group.getGroupname());
                    chat.setAvatar(group.getAvatar());
                    chat.setChatfrom(WxConstants.ChatFrom.SELF.getCode());
                    chat.setContent(atObject.toJSONString());
                    chat.setMsgtype(1);
                    chat.setSendstatus(WxErrorCode.INIT_VALUE);
                    chat.setReadstatus(Constants.YesNo.YES.ordinal());
                    chat.setFromplat(0);
                    chat.setShowstatus(Constants.YesNo.YES.getCode());
                    chat.setCsid(account.getCsid());
                    chat.setCreatetime(new Date());
                    chat.setReadtime(new Date());
                    chatService.sendChatByCmd(chat);
                    chatService.sendToKf(chat, group);
                }
            }

            for (WxWelcomTask task : tasks) {
                task.setMsgcount(task.getMsgcount()+1);
                task.setUpdatetime(new Date());
                welcomTaskDao.updateByPrimaryKey(task);
            }
            if (sent )
                return;
        }

    }
}
